﻿using System;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace RainyPWS.Common
{
    public class Utils
    {
        private static Regex RegexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
        private static Regex RegexSpace = new Regex(@"(\s)", RegexOptions.IgnoreCase);

        #region "js信息提示框"
        /// <summary>
        /// 消息对话框
        /// </summary>
        /// <param name="page"></param>
        /// <param name="msg"></param>
        public static void MsgBox(System.Web.UI.Page page, string msg)
        {
            string alert = "<script language='javascript'>alert('" + msg + "');</script>";
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "msg", alert);
        }

        public static void MsgBox(System.Web.UI.Page page, string msg, string ReturnUrl)
        {
            string alert = "<script language='javascript'>alert('" + msg + "'); location.href='" + ReturnUrl + "'</script>";
            page.ClientScript.RegisterClientScriptBlock(page.GetType(), "msgto", alert);
        }

        public static void LoadTinyEditor(System.Web.UI.Page page)
        {
            page.ClientScript.RegisterClientScriptInclude("TinyEditor", "/Scripts/tiny_mce_config.js");
        }

        public static void ModalDialogClose(System.Web.UI.Page page, string returnValue)
        {
            StringBuilder script = new StringBuilder();
            script.Append("window.returnValue = '" + returnValue + "';");
            script.Append("window.close();");
            page.ClientScript.RegisterStartupScript(page.GetType(), "dialogClose", script.ToString(), true);
        }

        #endregion

        #region 数据类型转换
        /// <summary>
        /// 将对象转换为Int32类型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static int StrToInt(object Expression, int defValue)
        {

            if (Expression != null)
            {
                string str = Expression.ToString();
                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*$"))
                {
                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                    {
                        return Convert.ToInt32(str);
                    }
                }
            }
            return defValue;
        }

        /// <summary>
        /// string型转换为float型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的int类型结果</returns>
        public static float StrToFloat(object strValue, float defValue)
        {
            if ((strValue == null) || (strValue.ToString().Length > 10))
            {
                return defValue;
            }

            float intValue = defValue;
            if (strValue != null)
            {
                bool IsFloat = Regex.IsMatch(strValue.ToString(), @"^([-]|[0-9])[0-9]*(\.\w*)?$");
                if (IsFloat)
                {
                    intValue = Convert.ToSingle(strValue);
                }
            }
            return intValue;
        }

        /// <summary>
        /// string型转换为bool型
        /// </summary>
        /// <param name="strValue">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>转换后的bool类型结果</returns>
        public static bool StrToBool(object Expression, bool defValue)
        {
            if (Expression != null)
            {
                if (string.Compare(Expression.ToString(), "true", true) == 0)
                {
                    return true;
                }
                else if (string.Compare(Expression.ToString(), "false", true) == 0)
                {
                    return false;
                }
            }
            return defValue;
        }

        /// <summary>
        /// string类型转为datetime类型
        /// </summary>
        /// <param name="Expression">要转换的字符串</param>
        /// <param name="defValue">缺省值</param>
        /// <returns></returns>
        public static DateTime StrToDate(object Expression, DateTime defValue)
        {
            if (Expression != null)
            {
                try
                {
                    DateTime temp = Convert.ToDateTime(Expression);
                    return temp;
                }
                catch
                {
                    return defValue;
                }
            }
            else
                return defValue;
        }

        /// <summary>
        /// 返回标准时间
        /// </summary>
        /// <param name="fdate"></param>
        /// <param name="formatstr">时间格式</param>
        /// <returns></returns>
        public static string GetStandardDateTime(string fdate, string formatstr)
        {
            DateTime t = StrToDate(fdate, DateTime.Now);
            return t.ToString(formatstr);
        }

        /// <summary>
        /// 返回标准日期格式
        /// </summary>
        /// <param name="fdate"></param>
        /// <returns></returns>
        public static string GetStandardDate(string fdate)
        {
            return GetStandardDateTime(fdate, "yyyy-MM-dd");
        }
        #endregion

        #region 数据类型判断
        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            if (Expression != null)
            {
                string str = Expression.ToString();
                if (str.Length > 0 && str.Length <= 11 && Regex.IsMatch(str, @"^[-]?[0-9]*[.]?[0-9]*$"))
                {
                    if ((str.Length < 10) || (str.Length == 10 && str[0] == '1') || (str.Length == 11 && str[0] == '-' && str[1] == '1'))
                    {
                        return true;
                    }
                }
            }
            return false;

        }

        /// <summary>
        /// 判断对象是否为双进度类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsDouble(object Expression)
        {
            if (Expression != null)
            {
                return Regex.IsMatch(Expression.ToString(), @"^([0-9])[0-9]*(\.\w*)?$");
            }
            return false;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        #endregion

        #region 格式化字符串,符合SQL语句
        /// <summary>
        /// 格式化字符串,符合SQL语句
        /// </summary>
        /// <param name="formatStr">需要格式化的字符串</param>
        /// <returns>字符串</returns>
        public static string inSQL(string formatStr)
        {
            string rStr = formatStr;
            if (formatStr != null && formatStr != string.Empty)
            {
                rStr = rStr.Replace("'", "''");
                rStr = rStr.Replace("\"", "\"\"");
            }
            return rStr;
        }
        /// <summary>
        /// 格式化字符串,是inSQL的反向
        /// </summary>
        /// <param name="formatStr"></param>
        /// <returns></returns>
        public static string outSQL(string formatStr)
        {
            string rStr = formatStr;
            if (rStr != null)
            {
                rStr = rStr.Replace("''", "'");
                rStr = rStr.Replace("\"\"", "\"");
            }
            return rStr;
        }

        /// <summary>
        /// 查询SQL语句,删除一些SQL注入问题
        /// </summary>
        /// <param name="formatStr">需要格式化的字符串</param>
        /// <returns></returns>
        public static string querySQL(string formatStr)
        {
            string rStr = formatStr;
            if (rStr != null && rStr != "")
            {
                rStr = rStr.Replace("'", "");
            }
            return rStr;
        }

        /// <summary>
        /// 返回字符串真实长度, 1个汉字长度为2
        /// </summary>
        /// <returns></returns>
        public static int GetStringLength(string str)
        {
            return Encoding.Default.GetBytes(str).Length;
        }

        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        startIndex = startIndex - length;
                    }
                }


                if (startIndex > str.Length)
                {
                    return "";
                }


            }
            else
            {
                if (length < 0)
                {
                    return "";
                }
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                    {
                        return "";
                    }
                }
            }

            if (str.Length - startIndex < length)
            {
                length = str.Length - startIndex;
            }

            try
            {
                return str.Substring(startIndex, length);
            }
            catch
            {
                return str;
            }
        }

        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的了符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }

        /// <summary>
        /// 从字符串的开始位置截取指定长度的子字符串(并替换成想要的字符)
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="length">子字符串的长度</param>
        /// <param name="replaceStr">想要的字符</param>
        /// <returns>子字符串</returns>
        public static string CutString(string str, int length, string replaceStr)
        {
            if (str.Length > length)
                return CutString(str, 0, length) + replaceStr;
            else
                return CutString(str, 0);
        }

        /// <summary>
        /// 给定字符串中的回车及换行符换成指定字符
        /// </summary>
        /// <param name="str">要清除的字符串</param>
        /// <param name="strx">指定字符</param>
        /// <returns>返回的字符串</returns>
        public static string ChangeBR(string str, string strx)
        {
            //Regex r = null;
            Match m = null;

            //r = new Regex(@"(\r\n)",RegexOptions.IgnoreCase);
            for (m = RegexBr.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), strx);
            }
            return str;
        }

        /// <summary>
        /// 清除给定字符串中的回车及换行符
        /// </summary>
        /// <param name="str">要清除的字符串</param>
        /// <returns>清除后返回的字符串</returns>
        public static string ClearBR(string str)
        {
            return ChangeBR(str, "");
        }

        public static string ClearHtml(string str)
        {
            Regex RegexHtml = new Regex("<.+?>|</.+?>");
            Match m = null;
            for (m = RegexHtml.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), "");
            }
            return str;
        }

        /// <summary>
        /// 转换空格
        /// </summary>
        /// <param name="str"></param>
        /// <param name="strx"></param>
        /// <returns></returns>
        public static string ChangeSpace(string str, string strx)
        {
            Match m = null;
            for (m = RegexSpace.Match(str); m.Success; m = m.NextMatch())
            {
                str = str.Replace(m.Groups[0].ToString(), strx);
            }
            return str;
        }

        /// <summary>
        /// 将用户输入的字符串转换为可换行、替换Html编码、无危害数据库特殊字符、去掉首尾空白、的安全方便代码。
        /// </summary>
        /// <param name="inputString">用户输入字符串</param>
        public static string ConvertStr(string inputString)
        {
            string retVal = inputString;
            retVal = retVal.Replace("&", "&amp;");
            retVal = retVal.Replace("\"", "&quot;");
            retVal = retVal.Replace("<", "&lt;");
            retVal = retVal.Replace(">", "&gt;");
            retVal = retVal.Replace(" ", "&nbsp;");
            retVal = retVal.Replace("  ", "&nbsp;&nbsp;");
            retVal = retVal.Replace("\t", "&nbsp;&nbsp;");
            retVal = retVal.Replace("\r", "<br>");
            return retVal;
        }
        /// <summary>
        /// 返回 HTML 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string HtmlEncode(string str)
        {
            return HttpUtility.HtmlEncode(str);
        }

        /// <summary>
        /// 返回 HTML 字符串的解码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string HtmlDecode(string str)
        {
            return HttpUtility.HtmlDecode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>编码结果</returns>
        public static string UrlEncode(string str)
        {
            return HttpUtility.UrlEncode(str);
        }

        /// <summary>
        /// 返回 URL 字符串的编码结果
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>解码结果</returns>
        public static string UrlDecode(string str)
        {
            return HttpUtility.UrlDecode(str);
        }

        /// <summary>
        /// 如果为空字符串，就用指定字符串来替换
        /// </summary>
        /// <param name="str"></param>
        /// <param name="reStr"></param>
        /// <returns></returns>
        public static string IsNulltoStr(string str, string reStr)
        {
            if (string.IsNullOrEmpty(str))
                return reStr;
            else
                return str;
        }
        #endregion

        #region 其他
        /// <summary>
        /// 得到项目的真实路径
        /// </summary>
        /// <returns></returns>
        public static string GetTrueProjectPath()
        {
            string projectPath = HttpContext.Current.Request.Path;
            if (projectPath.LastIndexOf("/") != projectPath.IndexOf("/"))
            {
                projectPath = projectPath.Substring(projectPath.IndexOf("/"), projectPath.LastIndexOf("/") + 1);
            }
            else
            {
                projectPath = "/";
            }
            return projectPath;
        }

        /// <summary>
        /// 获得项目的根目录
        /// </summary>
        /// <returns></returns>
        public static string GetProjectRoot()
        {
            string projectPath = HttpContext.Current.Request.Path;
            if (projectPath.ToLower().IndexOf("/admin/") != -1)
            {
                projectPath = projectPath.Substring(projectPath.IndexOf("/"), projectPath.ToLower().IndexOf("/admin/"));
            }
            else
            {
                projectPath = GetTrueProjectPath();
            }
            return projectPath;
        }

        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }

        /// <summary>
        /// 获得物理路径
        /// </summary>
        /// <param name="a">路径</param>
        /// <returns>物理路径</returns>
        public static string GetFullPath(string a)
        {
            string AppDir = System.AppDomain.CurrentDomain.BaseDirectory;
            if (a.IndexOf(":") < 0)
            {
                string str = a.Replace("..\\", "");
                if (str != a)
                {
                    int Num = (a.Length - str.Length) / ("..\\").Length + 1;
                    for (int i = 0; i < Num; i++)
                    {
                        AppDir = AppDir.Substring(0, AppDir.LastIndexOf("\\"));
                    }
                    str = "\\" + str;

                }
                a = AppDir + str;
            }
            return a;
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (null == result || result == String.Empty || !Utils.IsIP(result))
            {
                return "0.0.0.0";
            }

            return result;
        }

        /// <summary>
        /// 生成0-9随机数
        /// </summary>
        /// <param name="count">生成长度</param>
        /// <returns></returns>
        public static string RndNumStr(int count)
        {
            StringBuilder sb = new StringBuilder(count);
            Random rand = new Random();
            for (int i = 0; i < count; i++)
            {
                int temp = rand.Next(9);
                sb.AppendFormat("{0}", temp);
            }
            return sb.ToString();
        }

        /// <summary>
        /// 生成指定数值段之间的随机数
        /// </summary>
        /// <param name="minNum">最小值</param>
        /// <param name="maxNum">最大值</param>
        /// <returns></returns>
        public static int RndNumInt(int minNum, int maxNum)
        {
            Random rand = new Random();
            return rand.Next(minNum, maxNum);
        }

        /// <summary>
        /// 获取session中的值
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
        public static string getSession(string keys)
        {
            Object o = HttpContext.Current.Session[keys];
            if (o != null)
            {
                return o.ToString();
            }
            else
                return "";
        }

        /// <summary>
        /// MD5函数
        /// </summary>
        /// <param name="str">原始字符串</param>
        /// <returns>MD5结果</returns>
        public static string MD5(string str)
        {
            byte[] b = Encoding.UTF8.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

        /// <summary>
        /// SHA256函数
        /// </summary>
        /// /// <param name="str">原始字符串</param>
        /// <returns>SHA256结果</returns>
        public static string SHA256(string str)
        {
            byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
            SHA256Managed Sha256 = new SHA256Managed();
            byte[] Result = Sha256.ComputeHash(SHA256Data);
            return Convert.ToBase64String(Result);  //返回长度为44字节的字符串
        }
        #endregion
    }
}
